<?php

namespace AppVue\Http\Controllers;

use AppVue\Http\Models\ResponseResult;
use AppVue\Models\Record;
use AppVue\Models\RecordChild;
use Illuminate\Http\Request;
use Illuminate\Support\Collection;
use Log;
use Validator;

class RecordController extends Controller
{
    public function append(Request $request)
    {
        $record = null;
        if ($request->has('id')) {
            $record = Record::find($request->get('id'));
        }
        return view('record.append', compact('record'));
    }

    public function view(Request $request)
    {
        $q = $request->get('q');
        if (!empty($q)) {
            $search = '%' . $q . '%';
            $records = Record::where('name', 'like', $search)
                ->orWhere('serial_number', 'like', $search)
                ->paginate(30);
        } else {
            $records = Record::paginate(30);
        }
        return view('record.view', compact('records', 'q'));
    }

    public function set(Request $request)
    {
        $params = $request->all();
        if (array_key_exists('id', $params)) {
            $v = $this->validatorDate($params, true);
            if ($v->fails()) {
                return redirect()->back()->withErrors($v->getMessageBag()->getMessages());
            }

        } else {
            $v = $this->validatorDate($params, false);
            if ($v->fails()) {
                return redirect()->back()->withErrors($v->getMessageBag()->getMessages());
            }
        }

        $this->createdRecord($params);
        return redirect()->back()->with('success', '创建成功');
    }

    public function delete(Request $request)
    {

        $v = Validator::make($request->all(), ['id' => 'required|exists:records,id',]);
        if ($v->fails()) {
            return 'id不存在';
        }
        Record::destroy($request->get('id'));
        return 'OK';
    }

    public function recordView($id)
    {
        $record = Record::find($id);
        $childs = array();
        if (!empty($record)) {
            $childs = $record->child()->get();
        }
        return view('record', compact('record', 'childs'));
    }

    /**
     * @param array $data
     * @param bool $hasId
     * @return \Illuminate\Validation\Validator
     */
    private function validatorDate(array $data, bool $hasId)
    {
        $rules = [
            'name' => 'required|min:2|max:64',
            'serial_number' => 'required|min:2|max:64',
            'common' => '',
            'sex' => 'min:1',
            'images' => 'array',
        ];
        if ($hasId == true) {
            array_push($rules, ['id' => 'required|exists:records,id']);
        }

        return Validator::make($data, $rules);
    }


    /**
     * @param array $data
     * @return Record
     */
    private function createdRecord(array $data)
    {
        if (array_key_exists('id', $data)) {
            $record = Record::find($data['id']);
        } else {
            $record = new Record();
        }

        unset($data['_token']);
        $date = date('Y-m-d');
        if (array_key_exists('date', $data)) {
            $date = date('Y-m-d', strtotime($data['date']));
        }
        unset($data['date']);
        $record->setRawAttributes($data);
        $record->date = $date;
        if (array_key_exists('images', $data)) {
            $record->images = json_encode($data['images']);
        } else {
            $record->images = null;
        }
        Log::info($record);
        $record->save();
        return $record;
    }

    public function addChild(Request $request)
    {
        $v = Validator::make($request->all(), [
            'id' => 'required|exists:records,id',
            'title' => 'required|max:128'
        ]);
        if ($v->fails()) {
            return redirect()->back()->with('error', '创建子记录失败');
        }
        $rc = new RecordChild();
        $rc->records_id = $request->get('id');
        $rc->title = $request->get('title');
        if ($request->has('description')) {
            $rc->description = $request->get('description');
        } else {
            $rc->description = '';
        }
        $rc->save();
        return redirect()->back()->with('success', '创建子记录成功');
    }

    public function delChild(Request $request)
    {
        $v = Validator::make($request->all(), [
            'id' => 'required|exists:record_children,id',
        ]);
        if ($v->fails()) {
            return '删除子记录失败 ID 不存在';
        }
        RecordChild::destroy($request->get('id'));
        return 'OK';
    }

    public function recordChildView($id) {
        $child = RecordChild::find($id);
        if (empty($child)) {
            return redirect('/index');
        }

        return view('child', compact('child'));
    }

    public function editChild(Request $request) {
        $child = null;
        if ($request->has('id')) {
            $child = RecordChild::find($request->get('id'));
        }
        return view('record.child_edit', compact('child'));
    }

    public function editChildP(Request $request) {
        $v = Validator::make($request->all(), [
            'id' => 'required|exists:record_children,id',
            'title' => 'required|max:128'
        ]);

        if ($v->fails()) {
            return redirect()->back()->with('error', '更新子记录失败');
        }

        $child = RecordChild::find($request->get('id'));
        $child->title = $request->get('title');
        if ($request->has('description')) {
            $child->description = $request->get('description');
        } else {
            $child->description = '';
        }
        $child->save();
        return redirect()->back()->with('success', '更新子记录成功');
    }
}
